package org.xbzheng.restful_study.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.xbzheng.restful_study.model.User;
import org.xbzheng.restful_study.service.UserService;
import org.xbzheng.restful_study.util.ScrumConstant;

import javax.servlet.http.HttpSession;

/**
 * Created by szheng on 2016/10/27.
 */
@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager customAuthenticationManager;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(User user, HttpSession session){
        User loginUser = userService.login(user);
        if(loginUser != null ){
            session.setAttribute("loginUser", loginUser);
            Authentication authentication = customAuthenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
            SecurityContext securityContext = SecurityContextHolder.getContext();
            securityContext.setAuthentication(authentication);

            session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);

            session.setAttribute(ScrumConstant.USER, loginUser);
            //return "redirect:/index/";
            return "index";
        }
        return "login";
    }
}

